﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Auth;
using WalkingTec.Mvvm.Mvc;
using BathhouseService.ViewModels.HomeVMs;
using BathhouseService.Models.SqlModels;
using BathhouseService.Models.Commonality;
using System;
using Microsoft.EntityFrameworkCore;

namespace BathhouseService.Controllers
{
    public class HomeController : BaseController
    {
        [AllRights]
        public IActionResult Index()
        {
            ViewData["title"] = "WTM";
            return View();
        }

        [Public]
        public IActionResult PIndex()
        {
            return View();
        }

        [AllRights]
        [ActionDescription("首页")]
        public IActionResult FrontPage()
        {
            var date = DateTime.Now;
            var startMonth = DateCalculation.StartMonth(date);
            var endMonth = DateCalculation.EndMonth(date);
            var tclist = DC.Set<RechargeRecord>().ToList();
            var bzlist = DC.Set<PaymentRecord>().ToList();
            var tclistm = DC.Set<RechargeRecord>().Where(x => x.PaymentTime > startMonth && x.PaymentTime < endMonth).ToList();
            var bzlistm = DC.Set<PaymentRecord>().Where(x => x.PaymentTime > startMonth && x.PaymentTime < endMonth).ToList();
            ViewBag.allsrm = tclistm.Sum(x => x.ActualPayment) + bzlistm.Sum(x => x.ActualPayment);
            ViewBag.allsr = tclist.Sum(x => x.ActualPayment) + bzlist.Sum(x => x.ActualPayment);
            //月总收入
            ViewBag.tcsrm = tclistm.Sum(x => x.ActualPayment);
            ViewBag.bzsrm = bzlistm.Sum(x => x.ActualPayment);
            //年总收入
            ViewBag.tcsr = tclist.Sum(x => x.ActualPayment);
            ViewBag.bzsr = bzlist.Sum(x => x.ActualPayment);
            //售卡服务分析
            var skfx = DC.Set<ServiceRecord>()
                .Include(x => x.ValueAddedServices)
                .Where(x => x.PaymentTime > startMonth && x.PaymentTime < endMonth)
                .GroupBy(x => x.ValueAddedServices.Names)
                .Select(x => new
                {
                    value = x.Count(),
                    name = x.Key
                });
            ViewBag.skfx = skfx;
            ViewBag.skfxle = skfx.Select(x => x.name);
            var bzfx = DC.Set<PaymentRecord>()
                .Include(x=>x.ValueAddedServices)
                .Where(x => x.PaymentTime > startMonth && x.PaymentTime < endMonth)
                .GroupBy(x => x.ValueAddedServices.Names)
                .Select(x => new
                {
                    value = x.Count(),
                    name = x.Key
                });
            ViewBag.bzfx = skfx;
            ViewBag.bzfxle = skfx.Select(x => x.name);
            string cYear = DateTime.Now.Year.ToString();
            var yearStartEndMonth = DateCalculation.AllStartEndMonth(cYear);
            List<double> tcdlist = new List<double>();
            List<double> bzdlist = new List<double>();
            List<string> yflist = new List<string>();
            foreach (var item in yearStartEndMonth)
            {
                var tctemp = tclist.Where(x => x.PaymentTime > item.StartMonth && x.PaymentTime < item.EndMonth);
                var bztemp = bzlist.Where(x => x.PaymentTime > item.StartMonth && x.PaymentTime < item.EndMonth);
                var yf = item.StartMonth.ToString("yyyy年MM月");
                tcdlist.Add(tctemp.Sum(x => x.ActualPayment));
                bzdlist.Add(bztemp.Sum(x => x.ActualPayment));
                yflist.Add(yf);
            }
            ViewBag.tcdlist = tcdlist;
            ViewBag.bzdlist = bzdlist;
            ViewBag.yflist = yflist;
            return PartialView();
        }

        [AllRights]
        [ActionDescription("Layout")]
        public IActionResult Layout()
        {
            ViewData["debug"] = ConfigInfo.IsQuickDebug;
            return PartialView();
        }

        [AllRights]
        public IActionResult UserInfo()
        {
            if (HttpContext.Request.Cookies.TryGetValue(CookieAuthenticationDefaults.CookiePrefix + AuthConstants.CookieAuthName, out string cookieValue))
            {
                var protectedData = Base64UrlTextEncoder.Decode(cookieValue);
                var dataProtectionProvider = HttpContext.RequestServices.GetRequiredService<IDataProtectionProvider>();
                var _dataProtector = dataProtectionProvider
                                        .CreateProtector(
                                            "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                                            CookieAuthenticationDefaults.AuthenticationScheme,
                                            "v2");
                var unprotectedData = _dataProtector.Unprotect(protectedData);

                string cookieData = Encoding.UTF8.GetString(unprotectedData);
                return Json(cookieData);
            }
            else
                return Json("无数据");
        }

        [AllowAnonymous]
        [ResponseCache(Duration = 3600)]
        public github GetGithubInfo()
        {
            var rv = ReadFromCache<github>("githubinfo", () =>
            {
                var s = ConfigInfo.Domains["github"].CallAPI<github>("repos/dotnetcore/wtm", null, null, 60).Result;
                return s;
            }, 1800);

            return rv;
        }

        public class github
        {
            public int stargazers_count { get; set; }
            public int forks_count { get; set; }
            public int subscribers_count { get; set; }
            public int open_issues_count { get; set; }
        }

    }
}
